//
//  ZSNewsChannelView.m
//  fangwangyi
//
//  Created by 臧松 on 16/4/26.
//  Copyright © 2016年 zangsong. All rights reserved.
//

#import "ZSNewsChannelView.h"
#import "ZSNewsChannelViewCell.h"
#import "ZSChannel.h"
#define kChannnelViewCellId @"ChannnelViewCellId"

@interface ZSNewsChannelView ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong) NSMutableArray * channels;
@property (nonatomic,strong) ZSNewsChannelViewCell * cell;
@property (nonatomic,strong) NSIndexPath * indexPath;

@end
@implementation ZSNewsChannelView
// 懒加载
-(NSMutableArray *)channels{
    if (_channels == nil) {
        _channels = [NSMutableArray array];
    }
    return _channels;
}
-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {
        
        self.backgroundColor = [UIColor grayColor];
        // 取消滚动条
        self.showsHorizontalScrollIndicator = NO;
        // 取消弹簧效果
        self.bounces = NO;
        
        // 注册 cell
        [self registerClass:[ZSNewsChannelViewCell class] forCellWithReuseIdentifier:kChannnelViewCellId];
        // 获得数据
        [self getServerData];
        // 设置数据源
        self.dataSource = self;
        // 设置代理
        self.delegate = self;
        
        // 注册接受新闻主界面滚动的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changedChannel:) name:@"newsDataChanged" object:nil];
    }
    return self;
}
// 根据相应的 index 滚动到对应的 index
-(void)changedChannel:(NSNotification*)notify{
    NSIndexPath * indexPath = notify.object;
    
    // 滚动到对应的 index
    //[self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    
    // 选中 cell
    [self selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    ZSNewsChannelViewCell * cell = (ZSNewsChannelViewCell*)[self cellForItemAtIndexPath:indexPath];
    
    ZSChannel * channel = self.channels[indexPath.item];
    cell.channel = channel;
    
    // 刷新数据
    [self reloadItemsAtIndexPaths:@[indexPath]];
}

// 冲服务器获得新闻数据
-(void)getServerData{
    // 创建网络请求
    NSURL * url = [NSURL URLWithString:@"http://localhost/topic_news.json"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
        
        //NSLog(@"%@",response);
        if (data) {
           // NSLog(@"%@",data);
            NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            //NSLog(@"%@",dataDict[@"tList"]);
            NSArray * dataArray = dataDict[@"tList"];
            
            for (NSDictionary * dict in dataArray) {
                
                ZSChannel * channel = [ZSChannel channelWithDict:dict];
                // NSLog(@"%@",channel);
                // 添加到模型数组中
                [self.channels addObject:channel];
                 //NSLog(@"%@",self.channels);
            }
            
            // 发送通知,将新闻频道数据传递给新闻主界面
            [[NSNotificationCenter defaultCenter]postNotificationName:@"channelData" object:self.channels];
            // 刷新数据源
            [self reloadData];
            
            
        }
    }];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //NSLog(@"%lu",(unsigned long)self.channels.count);
    return self.channels.count;
}
#pragma mark - UICollectionViewDelegate

// 选中 item 的时候就会调用这个方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ZSChannel * channel = self.channels[indexPath.item];
    ZSNewsChannelViewCell * cell = (ZSNewsChannelViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.channel = channel;
    
    // 通知新闻主界面滚动
    [[NSNotificationCenter defaultCenter]postNotificationName:@"channelChanged" object:indexPath];
    
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZSChannel * channel = self.channels[indexPath.item];
    ZSNewsChannelViewCell * cell = (ZSNewsChannelViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    
    
    cell.channel = channel;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZSNewsChannelViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:kChannnelViewCellId forIndexPath:indexPath];
        
    ZSChannel * channel = self.channels[indexPath.item];
    cell.channel = channel;
    
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 计算每  一个 item 的大小
    ZSChannel *channel = self.channels[indexPath.item];
    
    return  [self getItemSizeWithString:channel.tname];
}
// 动态改变 item 的大小
-(CGSize)getItemSizeWithString:(NSString*)tname{
    
    UILabel * label = [[UILabel alloc]init];
    label.text = tname;
    [label sizeToFit];
    return label.bounds.size;
}
@end
